package com.doitdroid;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {

	private static final String TAG = "DoItDroid_DatabaseHelper";
	private static final String DATABASE_NAME = "doitdroid.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TASK_TABLE_NAME = "task";
    private static final String TASK_LIST_TABLE_NAME = "tasklist";
	private static final String _DefaultListName = "Active";
	
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    	String taskListTableTemplate = "CREATE TABLE %s ("
        + "%s INTEGER PRIMARY KEY,"
        + "%s TEXT"
        + ");";
    	String taskListTableStatement = String.format(taskListTableTemplate, TASK_LIST_TABLE_NAME, TaskListInfo.TaskList._ID, TaskListInfo.TaskList.TITLE);
    	db.execSQL(taskListTableStatement);
    	
    	ContentValues values = new ContentValues(1);
    	values.put(TaskListInfo.TaskList.TITLE, _DefaultListName);
    	db.insert(TASK_LIST_TABLE_NAME, TaskListInfo.TaskList.TITLE, values);
    	
    	String taskTableTemplate = "CREATE TABLE %s ("
            + "%s INTEGER PRIMARY KEY,"
            + "%s TEXT,"
            + "%s INTEGER,"
            + "%s INTEGER,"
            + "FOREIGN KEY(%s) REFERENCES %s(%s)"
            + ");";
        	String taskTableStatement = String.format(taskTableTemplate,
        			TASK_TABLE_NAME, 
        			TaskInfo.Task._ID, 
        			TaskInfo.Task.NAME, 
        			TaskInfo.Task.DUE_DATE,
        			TaskInfo.Task.LIST_ID,
        			TaskInfo.Task.LIST_ID,
        			TASK_LIST_TABLE_NAME,
        			TaskListInfo.TaskList._ID);
        	db.execSQL(taskTableStatement);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS" + TASK_LIST_TABLE_NAME);
        onCreate(db);
    }
}